package com.fc.push.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;

import com.fc.push.mqtt.pool.MqttClientPool;
import com.fc.push.mqtt.pool.MqttClientPoolConfig;

public class SharedMqttClientPoolImpl implements ISharedMqttClientPool{
	
	private static MqttClientPool mqttClientPool = null;
	
	private static MqttClientPoolConfig clientPoolConfig = null;
	private static MqttConnectOptions options = null;
	
	protected SharedMqttClientPoolImpl(String serverURI){
		clientPoolConfig = new MqttClientPoolConfig();
		clientPoolConfig.setMaxTotal(MqttConfig.getMaxTotal());
		clientPoolConfig.setMaxIdle(MqttConfig.getMaxIdle());
		clientPoolConfig.setMinIdle(MqttConfig.getMinIdle());
		clientPoolConfig.setMaxWaitMillis(MqttConfig.getMaxWaitMillis());
		clientPoolConfig.setTestOnBorrow(MqttConfig.isTestOnBorrow());
		clientPoolConfig.setTestWhileIdle(MqttConfig.isTestWhileIdle());
		clientPoolConfig.setTestOnCreate(MqttConfig.isTestOnCreate());
		clientPoolConfig.setTestOnReturn(MqttConfig.isTestOnReturn());
		
		options = new MqttConnectOptions();
		options.setCleanSession(MqttConfig.isCleanSession());
		options.setConnectionTimeout(MqttConfig.getConnectTimeOut());
		options.setKeepAliveInterval(MqttConfig.getKeepAliveInterval());
		if(MqttConfig.getUsername() != null && !MqttConfig.getUsername().isEmpty()){
			options.setUserName(MqttConfig.getUsername());
			options.setPassword(MqttConfig.getPassword().toCharArray());
		}
		mqttClientPool = new MqttClientPool(clientPoolConfig,serverURI,options);
	}
	
	@Override
	public MqttClient getResource() {
		return mqttClientPool.getResource();
	}

	@Override
	public void returnResource(MqttClient mqttClient) {
		mqttClientPool.returnResource(mqttClient);
	}

	@Override
	public void closePool() {
		mqttClientPool.close();
		mqttClientPool.destroy();
	}

	@Override
	public int getPoolIdles() {
		return mqttClientPool.getNumIdle();
	}

	@Override
	public int getPoolActives() {
		return mqttClientPool.getNumActive();
	}

	@Override
	public int getPoolWaiters() {
		return mqttClientPool.getNumWaiters();
	}
	
}
